import { defineComponent, reactive, onMounted, nextTick, computed, h, ref } from "vue";
import { ElButton, ElButtonGroup, ElMessageBox, ElIcon, ElSelect, ElOption } from "element-plus";
import { Plus, Close } from "@element-plus/icons-vue";

import { message } from "@/utils/Element";
import cssModule from "./index.module.scss";

import MonacoDditor from "@/components/Document/MonacoDditor/MonacoDditor.vue";
import { languageList } from "@/components/Document/WebEditor/menuConfig";

import type { PropType } from "vue";
import type { StateType, TemplateType } from "./type";

export default defineComponent({
  props: {
    /** v-model 绑定, 本地保存的所有模板 */
    modelValue: {
      type: Array as PropType<TemplateType[]>,
      default: () => []
    },
    /** 当前选中的模板 */
    templateActive: {
      type: Object as PropType<TemplateType>,
      default: () => []
    },
    /** 本地保存的 localStorage 的key前缀 */
    templateKeyPrefix: {
      type: String as PropType<string>,
      default: () => ""
    },
    /** 默认值 */
    defaultTemplates: {
      type: Array as PropType<TemplateType[]>,
      default: () => []
    }
  },
  emits: {
    "update:modelValue": (_val: TemplateType[]) => true,
    "update:templateActive": (_val: TemplateType) => true
  },
  setup(props, { emit }) {
    const state = reactive<StateType>({
      template: [],
      newTemplateName: "",
      monacoDditorlanguage: "javascript"
    });

    languageList;

    const _modelValue = computed({
      get() {
        return props.modelValue;
      },
      set(val) {
        emit("update:modelValue", val);
      }
    });

    const _templateActive = computed({
      get() {
        return props.templateActive;
      },
      set(val) {
        emit("update:templateActive", val);
      }
    });

    onMounted(() => {
      // 获取到指定的key
      const nativeKeys = Object.keys(window.localStorage).filter(key => key.startsWith(props.templateKeyPrefix));
      let templates: TemplateType[] = [];
      if (nativeKeys.length) {
        nativeKeys.forEach(key => {
          const val = window.localStorage.getItem(key);
          const name = key.replace(new RegExp("^" + props.templateKeyPrefix, ""), "").trim();
          templates.push({
            name,
            oldName: name,
            // 去掉内容前后的 " 不然文本格式会乱
            value: (val || "").replace(/^"*|"*$/g, ""),
            isInput: false
          });
        });

        _templateActive.value = templates[0];
      } else {
        templates = props.defaultTemplates;
        _templateActive.value = props.defaultTemplates[0];

        // 保存默认的模板到本地
        props.defaultTemplates.forEach(e => {
          window.localStorage.setItem(props.templateKeyPrefix + e.name, e.value || "");
        });
      }

      nextTick(() => {
        _modelValue.value = templates;
      });
    });

    const allNotInput = () => {
      const newTemplates = [..._modelValue.value];
      newTemplates.forEach(e => (e.isInput = false));
      _modelValue.value = newTemplates;
    };

    /** 保存模板 */
    const saveTemplate = () => {
      allNotInput();
      const newTemplateActive = { ..._templateActive.value };
      if (state.newTemplateName) {
        const newIdx = _modelValue.value.findIndex(e => e.name === state.newTemplateName);
        if (newIdx !== -1 && newTemplateActive !== _modelValue.value[newIdx]) {
          console.log("已经存放同名的模板无法保存");
          state.newTemplateName = "";
          return;
        }

        const newTemplates = [..._modelValue.value];
        const oldIdx = newTemplates.findIndex(e => e.name === _templateActive.value.oldName);
        if (oldIdx !== -1) {
          newTemplates[oldIdx].name = state.newTemplateName;
          _modelValue.value = newTemplates;
        }

        if (_templateActive.value) {
          newTemplateActive.name = state.newTemplateName;
          window.localStorage.removeItem(props.templateKeyPrefix + newTemplateActive.oldName);
          window.localStorage.setItem(props.templateKeyPrefix + state.newTemplateName, newTemplateActive.value || "");
          newTemplateActive.name = newTemplateActive.oldName = state.newTemplateName;
          newTemplateActive.isInput = false;
          state.newTemplateName = "";
        }
      } else {
        if (newTemplateActive.oldName) {
          window.localStorage.setItem(props.templateKeyPrefix + newTemplateActive.oldName, newTemplateActive.value);
        }
      }

      _templateActive.value = newTemplateActive;
    };

    /** 删除模板 */
    const deleteTemplate = () => {
      ElMessageBox.confirm("确定要删除该模板吗?", "提示", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning"
      }).then(() => {
        const newTemplates = [..._modelValue.value];
        const delItem = newTemplates.find(e => e === _templateActive.value);
        if (delItem) {
          window.localStorage.removeItem(props.templateKeyPrefix + delItem.oldName);
          _modelValue.value = newTemplates.filter(e => e !== _templateActive.value);
          _templateActive.value = {
            oldName: "",
            name: "",
            isInput: false,
            value: ""
          };
        } else {
          message.warning("数据删除失败");
        }
      });
    };

    const language = ref(state.monacoDditorlanguage);
    const setting = () => {
      ElMessageBox({
        title: "配置",
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        message: () =>
          h("div", null, [
            h("span", null, "语言: "),
            h(
              ElSelect,
              {
                placeholder: "选择需要设置的语言",
                size: "small",
                style: "width: 240px",
                modelValue: language.value,
                "onUpdate:modelValue": (val: string) => {
                  language.value = val;
                }
              },
              languageList.map((e, i) => {
                return h(ElOption, {
                  key: i,
                  label: e.label,
                  value: e.label
                });
              })
            )
          ])
      }).then(() => {
        state.monacoDditorlanguage = language.value;
      });
    };

    return () => (
      <div class={cssModule["full"]}>
        <ElButtonGroup>
          {_modelValue.value.map(e => {
            return (
              <ElButton
                key={e.name}
                type={e.name === _templateActive.value.name ? "primary" : "default"}
                onClick={() => {
                  if (_templateActive.value.name === e.name) {
                    allNotInput();
                    e.isInput = true;
                    state.newTemplateName = e.name;
                  } else {
                    saveTemplate();
                    _templateActive.value = e;
                  }
                }}
                v-slots={{
                  default: () => {
                    return e.isInput ? (
                      <div class={cssModule["template-input"]}>
                        <input
                          placeholder="请输入模板名"
                          v-model={state.newTemplateName}
                          onBlur={() => {
                            saveTemplate();
                          }}
                          onKeydown={event => {
                            if (event.key === "Enter") {
                              saveTemplate();
                            }
                          }}
                        />
                        <div
                          onClick={event => {
                            event.stopPropagation();
                            deleteTemplate();
                          }}
                        >
                          <ElIcon size={18} color="red">
                            <Close />
                          </ElIcon>
                        </div>
                      </div>
                    ) : (
                      <div>{e.name}</div>
                    );
                  }
                }}
              />
            );
          })}
        </ElButtonGroup>

        <ElButton
          type="default"
          style={{ marginLeft: "15px" }}
          icon={Plus}
          circle
          onClick={() => {
            saveTemplate();
            const newTemplates = [..._modelValue.value];
            const name = "newTemplate" + newTemplates.length;
            const newTemplate: TemplateType = {
              name,
              oldName: name,
              value: "",
              isInput: true
            };

            newTemplates.push(newTemplate);
            _modelValue.value = newTemplates;
            state.newTemplateName = newTemplate.name;
            _templateActive.value = newTemplate;
          }}
        />

        {/* 模板采用 ejs模板 */}
        <MonacoDditor
          style={{ marginTop: "10px", position: "relative" }}
          v-model={_templateActive.value.value}
          language={state.monacoDditorlanguage}
        >
          <div
            style={{
              position: "absolute",
              zIndex: 9999,
              right: "50px",
              bottom: "100px"
            }}
          >
            <ElButton type="primary" size="small" onClick={setting}>
              配置
            </ElButton>
          </div>
        </MonacoDditor>
      </div>
    );
  }
});
